/**
 * 
 */
package com.orange.controller.expert;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.orange.controller.BaseController;
import com.orange.dbhelp.page.Page;
import com.orange.handler.AuthSubjectService;
import com.orange.handler.expert.AuthSpecialTaskService;
import com.orange.modules.entity.expert.AuthSpecialTask;
import com.orange.modules.entity.manage.AuthSubject;
import com.orange.util.AppConfig;
import com.orange.util.ReturnCode;

/**
 * @author gaogs
 *
 * 2016-11-30
 */
@Controller
@RequestMapping("/authSpecialTask")
public class AuthSpecialTaskController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(AuthSpecialTaskController.class);
	
	@Autowired
	private AuthSpecialTaskService authSpecialTaskService;
	
	@Autowired
	private AppConfig appconfig;
	
	@Autowired
	private AuthSubjectService authSubjectService;
	
	
	/**
	 * 新建专业技能任务
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/saveAuthSpecialTaskInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> saveAuthSpecialTaskInfo(HttpServletRequest request,@RequestBody Map<String,String> map) throws SQLException{
		
		try{
			String url=map.get("url");//专业技能项目用表路径
			String name=map.get("name");//技能任务名称
			String type=map.get("type");//0：必测专业技能  1：选测专业技能  2：其他任务  
			String remark=map.get("remark");//0:无学科  1：有学科
			String major=map.get("major");//专业
			if(StringUtils.isBlank(name)||StringUtils.isBlank(remark)){
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "名称不能为空");
			}
			String nowTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			AuthSpecialTask a=new AuthSpecialTask();
			a.setCreateTime(nowTime);
			a.setName(name);
			a.setType(type);
			a.setRemark(remark);
			a.setMajor(major);
			if("0".equals(type)||"1".equals(type)){
				if(StringUtils.isBlank(url)){
					return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "专业技能项目用表路径不能为空");
				}
				String filename=url.substring(url.lastIndexOf("/")+1, url.length());
				a.setWordName(filename);
				a.setWordUrl(url);
			}
			authSpecialTaskService.saveAuthSpecialTaskInfo(a);
			return toResponse(null, ReturnCode.SUCCESS, "新建试题成功");
		}catch(Exception e){
			logger.info("新建试题失败", e);
			return toResponse(null,ReturnCode.FAIL,"新建试题失败");
		}
	}
	
	/**
	 * 专业技能项目用表
	 * @param filedata
	 * @return
	 */
	@RequestMapping(value="/uploadTask" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadFile(
			@RequestParam("file")MultipartFile filedata
			){
		try {
			String returnDatasUrl = null;
	  		String datasfile = appconfig.getFilePath();
	  		
	  		//取得可上传的文件类型  
	  		List<String>fileTypes = arrayToList(appconfig.getFileType().split(","));
	  		
	  		String fileName = filedata.getOriginalFilename();  
	  		//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
	  		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());  
	  		//对扩展名进行小写转换  
	  		ext = ext.toLowerCase();  
	  		/*//新的文件名
	  		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + 
	  				(int)(Math.random()*10000) + "." + ext;*/
	  		File file = null;
	  		if(!fileTypes.contains(ext)){
	  			return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"该文件类型不允许");
	  		}
	  		Long examSize=filedata.getSize();
	  		if(1.0*examSize/1024/1024>appconfig.getFileSize()){
	  			return toResponse(null,ReturnCode.FILE_SIZE_TOO_LONG,"文件大小超出限定上限");
	  		}
	  		
	  		Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH)+1;
            int d=cal.get(Calendar.DATE);
            Long nowTime=new Date().getTime();
            String pathbig=datasfile+y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
            file=new File(pathbig);
     		if(!file.exists()){
     			file.getParentFile().mkdirs();
     			file.createNewFile();
     		}
     		filedata.transferTo(file);
				
		    returnDatasUrl = y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
			return toResponse(returnDatasUrl,ReturnCode.SUCCESS,null);
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			return toResponse(null,ReturnCode.FAIL,"文件上传失败");
		}
	}
	
	   private List<String> arrayToList(String[] strs){
	    	List<String> list=new ArrayList<String>();
	    	if(strs.length>0){
	    		for(int a =0;a<strs.length;a++){
	    			list.add(strs[a].toString().trim());
	    		}
	    	}
			return list;
	    	
	    }
		/**
		 * 下载文档
		 * @param request
		 * @param response
		 * @param taskId
		 * @return
		 */
		@RequestMapping(value="/downloadFile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public void downloadFile(HttpServletRequest request,HttpServletResponse response ,@RequestParam String taskId){
			
			try {
				AuthSpecialTask a=authSpecialTaskService.queryAuthSpecialTaskInfoById(taskId);
				if(null==a){
					return ;
				}
				//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		        String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		        String filepath= a.getWordUrl();
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        
		        ServletOutputStream out;  
		        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
		        File file = new File(path +filepath);  
		  
		            FileInputStream inputStream = new FileInputStream(file);  
		  
		            //3.通过response获取ServletOutputStream对象(out)  
		            out = response.getOutputStream();  
		            try {
				         byte[] buffer = new byte[1024];  
				        /* while (b != -1){  
				            b = inputStream.read(buffer);  
				            //4.写到输出流(out)中  
				            out.write(buffer,0,b);  
				         } */
				         int count = 0;
				         while ((count = inputStream.read(buffer)) > 0) {
				        	 out.write(buffer, 0, count);
				         }
					} catch (Exception e) {
						logger.info("下载文件异常", e);
					}finally{
						inputStream.close();  
			            out.close();  
			            out.flush(); 
					}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		} 
	   
	   
		/**
		 * 修改专业技能任务
		 * @param request
		 * @param map
		 * @return
		 * @throws SQLException
		 */
		@RequestMapping(value = "/updateAuthSpecialTaskInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
		@ResponseBody
		public ResponseEntity<String> updateAuthSpecialTaskInfo(HttpServletRequest request,@RequestBody Map<String,String> map) throws SQLException{
			
			try{
				String url=map.get("url");//专业技能项目用表路径
				String name=map.get("name");//技能任务名称
				String pid=map.get("pid");//技能任务id
				if(StringUtils.isBlank(pid)||StringUtils.isBlank(name)||StringUtils.isBlank(url)){
					return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数存在空值");
				}
				AuthSpecialTask a=authSpecialTaskService.queryAuthSpecialTaskInfoById(pid);
				if(null==a){
					return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "该专业技能任务不存在");
				}
				String filename=url.substring(url.lastIndexOf("/")+1, url.length());
				a.setWordName(filename);
				a.setWordUrl(url);
				a.setName(name);
				authSpecialTaskService.saveAuthSpecialTaskInfo(a);
				return toResponse(null, ReturnCode.SUCCESS, "新建试题成功");
			}catch(Exception e){
				logger.info("新建试题失败", e);
				return toResponse(null,ReturnCode.FAIL,"新建试题失败");
			}
		}
		
	   
	   
	   
		/**
		 * 删除专业技能任务
		 * @param request
		 * @param map
		 * @return
		 * @throws SQLException
		 */
		@RequestMapping(value = "/deleteAuthSpecialTaskInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public ResponseEntity<String> deleteAuthSpecialTaskInfo(HttpServletRequest request,@RequestParam String pid) throws SQLException{
			
			try{
				if(StringUtils.isBlank(pid)){
					return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数存在空值");
				}
				AuthSpecialTask a=authSpecialTaskService.queryAuthSpecialTaskInfoById(pid);
				if(null==a){
					return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "该专业技能任务不存在");
				}
				authSpecialTaskService.deleteAuthSpecialTaskInfo(pid);
				
				if(a.getRemark().equals("1")){
					List<AuthSubject> as = authSubjectService.queryAuthSubjectByTaskId(pid);
					for (int i = 0; i < as.size(); i++) {
						authSubjectService.deleteAuthSubject(as.get(i).getPid());
					}
				}
				return toResponse(null, ReturnCode.SUCCESS, "删除专业技能任务成功");
			}catch(Exception e){
				logger.info("删除专业技能任务失败", e);
				return toResponse(null,ReturnCode.FAIL,"删除专业技能任务失败");
			}
		}
	
	
		/**
		 * 分页查询专业技能任务
		 * @param request
		 * @param map
		 * @return
		 * @throws SQLException
		 */
		@RequestMapping(value = "/queryAuthSpecialTaskPage" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
		@ResponseBody
		public ResponseEntity<String> queryauthSpecialTaskPage(HttpServletRequest request,@RequestBody Map<String,String> map) throws SQLException{
			
			try{
				String pageSize=map.get("pageSize");//专业技能项目用表路径
				String pageNumber=map.get("pageNumber");//技能任务名称
				
				if(StringUtils.isBlank(pageSize)||StringUtils.isBlank(pageNumber)){
					return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数存在空值");
				}
				Page<AuthSpecialTask> page= authSpecialTaskService.queryauthSpecialTaskPage(map);
				return toResponse(page, ReturnCode.SUCCESS, "分页查询专业技能任务成功");
			}catch(Exception e){
				logger.info("分页查询专业技能任务失败", e);
				return toResponse(null,ReturnCode.FAIL,"分页查询专业技能任务失败");
			}
		}
	
	/**
	 * 查询必测task
	 */
 
	@RequestMapping(value = "/queryTaskName" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> queryTaskName(HttpServletRequest request,@RequestParam String major) throws SQLException{
		try{
			List<AuthSpecialTask> list= authSpecialTaskService.queryTaskNameByType(major);
			
			return toResponse(list, ReturnCode.SUCCESS, "专业技能名称");
		}catch(Exception e){
			logger.info("专业技能失败", e);
			return toResponse(null,ReturnCode.FAIL,"专业技能失败");
		}
	}

}
